// utils/auth.ts
class AuthService {
  private tokenKey = '__login__';
  private userKey = '__login_info__';

  // 设置登录信息
  setAuth(token: string, userInfo: any, expiresIn: number = 24 * 60 * 60 * 1000) {
    const authData = {
      token,
      userInfo,
      expiresAt: Date.now() + expiresIn
    };
    localStorage.setItem(this.tokenKey, JSON.stringify(authData));
  }

  // 获取 token
  getToken(): string | null {
    const authData = this.getAuthData();
    return authData?.token || null;
  }

  // 获取用户信息
  getUserInfo(): any {
    const authData = this.getAuthData();
    return authData?.userInfo || null;
  }

  // 检查是否登录
  isAuthenticated(): boolean {
    const authData = this.getAuthData();
    if (!authData) return false;

    // 检查 token 是否过期
    if (authData.expiresAt && Date.now() > authData.expiresAt) {
      this.clearAuth();
      return false;
    }

    return !!authData.token;
  }

  // 清除认证信息
  clearAuth() {
    localStorage.removeItem(this.tokenKey);
    localStorage.removeItem(this.userKey);
  }

  // 获取认证数据
  private getAuthData(): any {
    try {
      const authData = localStorage.getItem(this.tokenKey);
      return authData ? JSON.parse(authData) : null;
    } catch {
      return null;
    }
  }
}

export const authService = new AuthService();